package com.jingan.nursinghome.regulatory.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

import com.jingan.nursinghome.regulatory.data.Scount;

import java.util.ArrayList;
import java.util.List;

import cn.android.support.v7.lib.sin.crown.base.BaseListenner;
import cn.android.support.v7.lib.sin.crown.base.BaseView;
import cn.android.support.v7.lib.sin.crown.utils.AssetsUtils;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;
import cn.android.support.v7.lib.sin.crown.utils.UtilToast;

/**
 * Created by 彭治铭 on 2017/9/30.
 */

public class SpannerChildView2 extends BaseView implements View.OnTouchListener {
    public SpannerChildView2(Context context) {
        super(context);
        init();
    }

    public SpannerChildView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    int strokeWidth = ProportionUtils.getInstance().adapterInt(6);
    int strockeColor = Color.parseColor("#C9C9C9");
    int subTextColor = Color.parseColor("#999999");
    int textSize = ProportionUtils.getInstance().adapterInt(30);
    int textBackground = Color.parseColor("#E9EEF2");

    List<Model> models;
    int width, height, lineHeight, maxHeight;

    BaseListenner<String> callBack;

    //设置信息
    public void setInfos(View view, List<String> infos, int count, BaseListenner<String> callBack) {
        width = view.getWidth() > view.getLayoutParams().width ? view.getWidth() : view.getLayoutParams().width;
        lineHeight = view.getHeight() > view.getLayoutParams().height ? view.getHeight() : view.getLayoutParams().height;
        height = lineHeight * count;
        maxHeight = lineHeight * infos.size();
        models = new ArrayList<>();
        for (int i = 0; i < infos.size(); i++) {
            Model model = new Model();
            model.info = infos.get(i).trim();
            model.textX = lineHeight * i + (lineHeight - textSize) / 2 + textSize;
            model.y1 = model.textX - textSize / 2 - lineHeight / 2;
            model.y2 = model.y1 + lineHeight;
            models.add(model);
        }
        this.callBack = callBack;
        requestLayout();
    }

    class Model {
        String info;
        int y1;
        int y2;
        int textX;
        boolean state = false;//是否选中
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    //位图,常态,选中
    Bitmap general, selected;

    private void init() {
        textPaint.setTextAlign(Paint.Align.LEFT);
        textPaint.setColor(subTextColor);
        textPaint.setTextSize(textSize);
        setOnTouchListener(this);
        scroller = new Scroller(this.getContext());

        general = AssetsUtils.getInstance().getBitmapFromAssets( "crown/selector/general.png", 0, true);
        selected = AssetsUtils.getInstance().getBitmapFromAssets( "crown/selector/selected.png", 0, true);
        general = ProportionUtils.getInstance().adapterBitmap(general);
        selected = ProportionUtils.getInstance().adapterBitmap(selected);
    }

    Scroller scroller;

    public void smoothScrollBy(int x, int y) {
        if (scroller != null && (x != getScrollX() || y != getScrollY())) {
            //getScrollX()代表起点坐标 参数一，二是起始点。
            //x,y不是具体的坐标，而是偏移量。如y=100,表示以起始点为标准移动100，不是移动到100. 参数三，四不是具体坐标，是偏移量。
            scroller.startScroll(getScrollX(), getScrollY(), x, y, 500);//这个方法只是保存了时间和坐标参数参数。不会调用任何滑动的方法。
            invalidate();//真正起作用的是这个方法。从新布局，会调用computeScroll()方法。
        }
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (scroller != null && scroller.computeScrollOffset()) {//true 继续滑动，false滑动结束【根据startScroll()里的时间参数来进行判断，时间没有到则返回true继续滑动，时间到了返回false 滑动结束】
            scrollTo(scroller.getCurrX(), scroller.getCurrY());//scroller里的时间和坐标是不断的刷新的。
            postInvalidate();//再次重新布局，又会调用computeScroll()
        }
    }

    GestureDetectorCompat gestureDetectorCompat = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            int scrollx = (int) (getScrollY() + distanceY);
            if (scrollx > 0 && scrollx < maxHeight - height + lineHeight / 10) {
                scrollTo(0, scrollx);
            }
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            int distanceY = (int) (e2.getY() - e1.getY());
            distanceY += distanceY;
            int scrollx = (int) (getScrollY() - distanceY);
            if (scrollx > 0 && scrollx < maxHeight - height + lineHeight / 10) {
                smoothScrollBy(0, -distanceY);
            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }

//        @Override
//        public void onShowPress(MotionEvent e) {
//            super.onShowPress(e);
//            onselect(e);
//        }

//        @Override
//        public boolean onDown(MotionEvent e) {
//            onselect(e);
//            return super.onDown(e);
//        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            onselect(e);
            return super.onSingleTapConfirmed(e);
        }
    });

    String selectName;

    int index = 0;//下标。

    public void setIndex(int index) {
        this.index = index;
    }

    int maxCount = 5;//最大选择个数。

    //根据坐标选中对应值
    void onselect(MotionEvent e) {
        selectName = "";
        for (int i = 0; i < models.size(); i++) {
            if (e.getY() + getScrollY() > models.get(i).y1 && e.getY() + getScrollY() < models.get(i).y2) {
                if (Scount.counts[index] < maxCount && !models.get(i).state) {
                    models.get(i).state = !models.get(i).state;
                    Scount.counts[index]++;
                } else if (Scount.counts[index] < maxCount && models.get(i).state) {
                    models.get(i).state = !models.get(i).state;
                    Scount.counts[index]--;
                } else if (Scount.counts[index] >= maxCount && models.get(i).state) {
                    models.get(i).state = !models.get(i).state;
                    Scount.counts[index]--;
                } else {
                    UtilToast.showToastView("最多只能选中五人");
                }
            }
            if (models.get(i).state) {
                if (selectName.equals("")) {
                    selectName = selectName + models.get(i).info;
                } else {
                    selectName = selectName + "、" + models.get(i).info;
                }
            }
        }
        invalidate();
        if (callBack != null) {
            callBack.onResult(selectName);
        }
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        if (models == null) {
            return;
        }
        //画背景
        canvas.drawColor(textBackground);
        //画边框
        paint.setColor(strockeColor);
        paint.setStrokeWidth(strokeWidth);
        paint.setStyle(Paint.Style.STROKE);
        //canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
        canvas.drawLine(0, 0, 0, getHeight() + getScrollY(), paint);//左
        //canvas.drawLine(0,0,0,getHeight(),paint);//上
        canvas.drawLine(getWidth(), 0, getWidth(), getHeight() + getScrollY(), paint);//右
        canvas.drawLine(0, getHeight() + getScrollY(), getWidth(), getHeight() + getScrollY(), paint);//下
        //設置信息
        for (int i = 0; i < models.size(); i++) {
            int y = models.get(i).textX - textSize / 3 * 2 - ProportionUtils.getInstance().adapterInt(4);
            if (models.get(i).state) {
                canvas.drawBitmap(selected, getWidth() - selected.getWidth() * 2, y, paint);
            } else {
                canvas.drawBitmap(general, getWidth() - selected.getWidth() * 2, y, paint);
            }
            canvas.drawText(models.get(i).info, (float) (textSize * 0.6), models.get(i).textX, textPaint);
        }

        if (height < maxHeight) {
            paint.setStrokeCap(Paint.Cap.ROUND);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setColor(Color.parseColor("#4B97F0"));

            int scrollWidth = strokeWidth * 2;//滑动条高度
            paint.setStrokeWidth(scrollWidth);
            paint.setStyle(Paint.Style.STROKE);
            int distance = (maxHeight - height);//最大滑动距离
            int scrollHeight = height - distance;//滑动条高度
            if (scrollHeight < scrollWidth * 3) {
                scrollHeight = scrollWidth * 3;
            }
            int scorollY = (int) ((float) getScrollY() / (float) distance * (height - scrollHeight));
            int y1 = (int) (getScrollY() + scorollY + scrollWidth);//滑动开始位置
            int y2 = y1 + scrollHeight - scrollWidth * 2;//滑动结束位置
            canvas.drawLine(getWidth() - strokeWidth / 2 - scrollWidth / 2, y1, getWidth() - strokeWidth / 2 - scrollWidth / 2, y2, paint);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        gestureDetectorCompat.onTouchEvent(event);
        return true;
    }
}
